package emails

import (
	"bytes"
	"crypto/tls"
	"engine/dto"
	"gopkg.in/gomail.v2"
	"html/template"
	"lib/log"
	"strconv"
	"strings"
)

func SendHtmlEmail(to string, cc string, bcc string, subject string, body string, attachments []string) {
	emailConfig, err := dto.GetEmailSmtpConfig()
	if err == nil && emailConfig != nil {
		if to == "" {
			to = emailConfig.From
		}
		m := gomail.NewMessage()
		m.SetHeader("From", emailConfig.From)
		m.SetHeaders(map[string][]string{
			"To": strings.Split(to, ","),
		})
		m.SetHeader("Subject", subject)
		if cc != "" {
			m.SetHeaders(map[string][]string{
				"Cc": strings.Split(cc, ","),
			})
		}
		if bcc != "" {
			m.SetHeaders(map[string][]string{
				"Bcc": strings.Split(bcc, ","),
			})
		}
		for _, attachment := range attachments {
			m.Attach(attachment)
		}
		m.SetBody("text/html", body)
		// 创建Dialer实例，用于连接SMTP服务器
		portInt, _ := strconv.Atoi(emailConfig.Port)
		d := gomail.NewDialer(emailConfig.SmtpHost, portInt, emailConfig.From, emailConfig.Password)
		d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
		// 发送邮件
		if mailErr := d.DialAndSend(m); mailErr != nil {
			// TODO 记录邮件发送失败的详细信息
			log.Errorf("发送邮件失败" + to)
		}
	}
}

func RenderTemplate(name string, data interface{}) string {
	t, err := template.ParseFiles(name)
	if err != nil {
		return ""
	} else {
		// 渲染模板到字符串
		var tpl bytes.Buffer
		if errs := t.Execute(&tpl, data); errs != nil {
			return ""
		}
		htmlContent := tpl.String()
		return htmlContent
	}
}
